package com.rxy.socketdemo

import android.app.Service
import android.content.Intent
import android.os.*
import android.util.Log
import android.widget.Toast
import java.io.*
import java.net.Socket

class SocketService : Service() {

    private var socket: Socket? = null
    private var writer: BufferedWriter? = null

    // Binder 对象，用于暴露服务接口
    private val binder = LocalBinder()

    inner class LocalBinder : Binder() {
        fun getService(): SocketService = this@SocketService
    }

    override fun onBind(intent: Intent?): IBinder? = binder

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent != null) {
            when (intent.action) {
                Constants.ACTION_CONNECT -> {
                    val ip = intent.getStringExtra(Constants.EXTRA_IP)
                    val port = intent.getIntExtra(Constants.EXTRA_PORT, -1)
                    connectToServer(ip, port)
                }
                Constants.ACTION_SEND -> {
                    val message = intent.getStringExtra(Constants.EXTRA_MESSAGE)
                    sendMessage(message)
                }
            }
        }
        return START_STICKY
    }

    // 获取当前连接状态
    fun isConnected(): Boolean {
        return socket != null && socket?.isConnected == true && !socket?.isClosed!!
    }

    private fun connectToServer(ip: String?, port: Int) {
        Thread {
            try {
                socket = Socket(ip, port)
                writer = BufferedWriter(OutputStreamWriter(socket?.getOutputStream()))
                Log.d("SocketService", "已连接到服务器")
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(baseContext, "已连接到服务器", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(baseContext, "连接服务器异常", Toast.LENGTH_SHORT).show()
                }
            }
        }.start()
    }

    fun sendMessage(message: String?) {
        Thread {
            try {
                if (isConnected()) {
                    writer?.write("$message\n")
                    writer?.flush()
                    Log.d("SocketService", "发送消息: $message")
                    Handler(Looper.getMainLooper()).post {
                        Toast.makeText(baseContext, "发送消息: $message", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    Log.e("SocketService", "未连接，无法发送消息")
                    Handler(Looper.getMainLooper()).post {
                        Toast.makeText(baseContext, "未连接，无法发送消息", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        writer?.close()
        socket?.close()
        Log.d("SocketService", "服务已销毁")
    }
}
